use RDF::Redland;
use HTTP::Daemon;
use HTTP::Status;

## DEFINE the Database
# DBName - store
# hash-type = bdb
# store on filesystem in db/
my $storage = new RDF::Redland::Storage (
                 "hashes",
                 "store",
                 "new='no', hash-type='bdb', dir='db/'")
     or die "Failed to create RDF::Redland::Storage\n";

## DEFINE the Model and link it to the store db
my $model = new RDF::Redland::Model ($storage, "")
     or die "Failed to create RDF::Redland::Model for storage\n";
     
my $query_string = "";
my $content;

##DEFINE beginning of the XHTML Document
my $webheader = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>
<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"
\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">

<html xmlns=\"http://www.w3.org/1999/xhtml\" xml:lang=\"de\" lang=\"de\">
	<head>
		<title>University</title>
	</head>
<body>
	<h1>";

## START DAEMON
 my $d = HTTP::Daemon->new(LocalPort => 12345,
 							Reuse => 1) || die;
 print "Please contact me at: <URL:", $d->url, ">\n";
 while (my $c = $d->accept) {
     while (my $r = $c->get_request) {
         print $r -> url->path . "\n";
         if ($r->method eq 'GET') {
                @uriPath = split( /\//, $r -> url->path );
                 if (@uriPath[1] eq "lva") {
                     print "Requested lva " . @uriPath[2];
                     ###.../lva/someCourse  SHOW a particular course ###
                     if (@uriPath[2] ne "") {
                    	 $content .= "Lehrveranstaltung</h1>";
                    	 $query_string = "SELECT ?Course ?Type ?ECTS ?SemHours ?coursetype
                                                         WHERE {
                                                         	   <http://tuwien.ac.at/lvs/course#" . @uriPath[2] . "> <http://tuwien.ac.at/lvs/CourseTitle> ?Course .
                                                               <http://tuwien.ac.at/lvs/course#" . @uriPath[2] . "> <http://tuwien.ac.at/lvs/CourseHasType> ?coursetype .
                                                               <http://tuwien.ac.at/lvs/course#" . @uriPath[2] . "> <http://tuwien.ac.at/lvs/ECTSCount> ?ECTS .
                                                               <http://tuwien.ac.at/lvs/course#" . @uriPath[2] . "> <http://tuwien.ac.at/lvs/SemesterHours> ?SemHours .
                                                               ?coursetype <http://purl.org/dc/elements/1.1/title> ?Type
                                                               
                                                         }";
                     	print "\n" . $query_string . "\n";
                     	### .../lva/  SHOW all courses ###
                     } else {
                     		$content .= "Lehrveranstaltungen</h1>";
                    	 $query_string = "SELECT ?Course ?Type ?ECTS ?SemHours ?coursetype ?lva
                                                         WHERE {
                                                         	   ?lva <http://tuwien.ac.at/lvs/CourseTitle> ?Course .
                                                               ?lva <http://tuwien.ac.at/lvs/CourseHasType> ?coursetype .
                                                               ?lva <http://tuwien.ac.at/lvs/ECTSCount> ?ECTS .
                                                               ?lva <http://tuwien.ac.at/lvs/SemesterHours> ?SemHours .
                                                               ?coursetype <http://purl.org/dc/elements/1.1/title> ?Type .
                                                               	
                                                         }
                                                         ORDER BY ?Course";
                     }
                     
                     my $query=new RDF::Redland::Query($query_string, undef, undef, 'sparql'); # default query language
                                 my $results=$query->execute($model);
                                 print $results;
                                 if ($results->count ne 0) {
                                 while(!$results->finished) {
                                 	$content .= "<ul>";
                                   for (my $i=0; $i < $results->bindings_count(); $i++) {
                                     my $name=$results->binding_name($i);
                                     my $value=$results->binding_value($i);
                                     
                                     
                                     if ($name eq "Course") {
                                     	$content .= "<li>" . $name . ": " .$value->literal_value ."</li>";
                                     } elsif ($name eq "ECTS") {
                                     	$content .= "<li>" . $name . ": " .$value->literal_value ."</li>";
                                     } elsif ($name eq "Type") {
                                     	$content .= "<li>" . $name . ": " .$value->literal_value ."</li>";
                                     } elsif ($name eq "SemHours") {
                                     	$content .= "<li>" . $name . ": " .$value->literal_value ."</li>";
                                     }
                                   }
                                   $content .="</ul>";
                                   $results->next_result;
                                 }
                                 
       
       					$content .= "</body>
       					</html>";
                                 
                      $header = HTTP::Headers->new(
                                      Content_Type => 'text/html; version=3.2',
                                      Content_Base => 'http://www.perl.org/');
                     my $res = HTTP::Response->new( HTTP_OK, "Itsy bitsy", $header, $webheader . $content );
                     $c->send_response($res);
                     $content = ""; ### clear content for new requests....
                                 } else {
                                 	$c->send_error(404);
                                 	$content = "";
                                 }
                     ### IF .../pruefungsfach  ###
                 } elsif (@uriPath[1] eq "pruefungsfach") {
                 	if (@uriPath[2] ne "") {
                 	$query_string = "SELECT ?ExamCourse ?Course ?oc ?id ?Titel ?id2
                 							WHERE {
                 									<http://tuwien.ac.at/lvs/examcourse#" . @uriPath[2] ."> <http://purl.org/dc/elements/1.1/title> ?ExamCourse .
                 									?oc <http://tuwien.ac.at/lvs/CourseOccurrenceHasExamCourse> <http://tuwien.ac.at/lvs/examcourse#" . @uriPath[2] ."> .
                 									?id <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> ?oc .
                 									?id2 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> ?id .
                 									?Course <http://tuwien.ac.at/lvs/CourseOccurrences> ?id2 .
                 									?Course <http://tuwien.ac.at/lvs/CourseTitle> ?Titel .
                 							}";
                 	print "\n" . $query_string . "\n";
                 	my $query=new RDF::Redland::Query($query_string, undef, undef, 'sparql'); # default query language
                                 my $results=$query->execute($model);
                                 my $examcoursetitle;
                                 my $restcontent="<ul>
                                 ";
                                 if($results->count ne 0){
                                 while(!$results->finished) {
                                   for (my $i=0; $i < $results->bindings_count(); $i++) {
                                     my $name=$results->binding_name($i);
                                     my $value=$results->binding_value($i);
                                     
                                     if ($name eq "ExamCourse") {
                                     	$examcoursetitle = "Prüfungsfächer für " . $value->literal_value . "</h1>";
                                     } elsif ($name eq "Titel") {
                                     	$restcontent .= "<li>" . $value->literal_value . "</li>"
                                     }
                                   
                                   }
                                   $results->next_result;
                                 }
                                 $content .= $examcoursetitle . $restcontent;
                                 $content .= "</ul>
       					</body>
       					</html>";
                    $header = HTTP::Headers->new(
                                      Content_Type => 'text/html; version=3.2',
                                      Content_Base => 'http://www.perl.org/');
                     my $res = HTTP::Response->new( HTTP_OK, "Itsy bitsy", $header, $webheader . $content);
                     $c->send_response($res);
                     $content = ""; # ... clear content for new requests.
                     	} else {
                 		$c->send_error(404);
                 		$content = "";
                 		}
                 	} else {
                 		$c->send_error(404);
                 		$content = "";
                 	}
                 	
                 	### For a particular instance ###
                 } elsif (@uriPath[1] eq "instance") {
                 	
                 	if (@uriPath[2] ne "") {
                 	$query_string = "SELECT ?courseuri ?Course ?Year ?Semester ?Begin ?End ?Lecturer
                 					WHERE {
                 							<http://tuwien.ac.at/lvs/courseinstance#" . @uriPath[2] ."> <http://tuwien.ac.at/lvs/InstanceOfCourse> ?courseuri .
                 							?courseuri <http://tuwien.ac.at/lvs/CourseTitle> ?Course .
                 							<http://tuwien.ac.at/lvs/courseinstance#" . @uriPath[2] ."> <http://tuwien.ac.at/lvs/CourseInstanceYear> ?Year .
                 							<http://tuwien.ac.at/lvs/courseinstance#" . @uriPath[2] ."> <http://tuwien.ac.at/lvs/CourseInstanceSemester> ?Semester .
                 							<http://tuwien.ac.at/lvs/courseinstance#" . @uriPath[2] ."> <http://tuwien.ac.at/lvs/CourseInstanceBegin> ?Begin .
                 							<http://tuwien.ac.at/lvs/courseinstance#" . @uriPath[2] ."> <http://tuwien.ac.at/lvs/CourseInstanceEnd> ?End .
                 							<http://tuwien.ac.at/lvs/courseinstance#" . @uriPath[2] ."> <http://tuwien.ac.at/lvs/CourseInstanceLecturer> ?Lecturer .
                 							
                 					}";
                 					print $query_string;
                 					$content .= "Course Instance</h1>";
                 my $query=new RDF::Redland::Query($query_string, undef, undef, 'sparql'); # default query language
                                 my $results=$query->execute($model);
                                 if ($results->count ne 0){
                                 while(!$results->finished) {
                                 	$content .= "<ul>";
                                   for (my $i=0; $i < $results->bindings_count(); $i++) {
                                     my $name=$results->binding_name($i);
                                     my $value=$results->binding_value($i);
                                     
                                     if ($name eq "Course") {
                                     	$content .= "<li>" . $name . ": " .$value->literal_value ."</li>";
                                     } elsif ($name eq "Year") {
                                     	$content .= "<li>" . $name . ": " .$value->literal_value ."</li>";
                                     } elsif ($name eq "Semester") {
                                     	$content .= "<li>" . $name . ": " .$value->literal_value ."</li>";
                                     } elsif ($name eq "Begin") {
                                     	$content .= "<li>" . $name . ": " .$value->literal_value ."</li>";
                                     } elsif ($name eq "End") {
                                     	$content .= "<li>" . $name . ": " .$value->literal_value ."</li>";
                                   	 } elsif ($name eq "Lecturer") {
                                     	$content .= "<li>" . $name . ": " .$value->literal_value ."</li>";
                                   	 }
                                   }
                                   $content .= "</ul>";
                                   $results->next_result;
                                 }
       
       					
       					$content .= "</body>
       					</html>";
                 	
                      $header = HTTP::Headers->new(
                                      Content_Type => 'text/html; version=3.2',
                                      Content_Base => 'http://www.perl.org/');
                     my $res = HTTP::Response->new( HTTP_OK, "Itsy bitsy", $header, $webheader . $content );
                     $c->send_response($res);
                     $content = ""; ### clear content for new requests....
                                 } else {
                                 	$c->send_error(404);
                                 	$content = "";
                                 }
                 	} else {
                 		$c->send_error(404);
                 		$content = "";
                 	}
                 
                 ### For all instances of a particular course ###
                 } elsif (@uriPath[1] eq "instances") {
                 	if (@uriPath[2] ne "") {
                 	$query_string = "SELECT ?courseinstanceuri ?Year ?Semester ?Begin ?End ?Lecturer
                 					WHERE {
                 							?courseinstanceuri <http://tuwien.ac.at/lvs/InstanceOfCourse> <http://tuwien.ac.at/lvs/course#" . @uriPath[2] .">.
                 							?courseinstanceuri <http://tuwien.ac.at/lvs/CourseInstanceYear> ?Year .
                 							?courseinstanceuri <http://tuwien.ac.at/lvs/CourseInstanceSemester> ?Semester .
                 							?courseinstanceuri <http://tuwien.ac.at/lvs/CourseInstanceBegin> ?Begin .
                 							?courseinstanceuri <http://tuwien.ac.at/lvs/CourseInstanceEnd> ?End .
                 							?courseinstanceuri <http://tuwien.ac.at/lvs/CourseInstanceLecturer> ?Lecturer .
                 							
                 					}";
                 					print $query_string;
                 					$content .= "Course Instances</h1>";
                 my $query=new RDF::Redland::Query($query_string, undef, undef, 'sparql'); # default query language
                                 my $results=$query->execute($model);
                                 
                                 if ($results->count ne 0) {
                                 while(!$results->finished) {
                                 	$content .= "<ul>";
                                   for (my $i=0; $i < $results->bindings_count(); $i++) {
                                     my $name=$results->binding_name($i);
                                     my $value=$results->binding_value($i);
                                     
                                     if ($name eq "Course") {
                                     	$content .= "<li>" . $name . ": " .$value->literal_value ."</li>";
                                     } elsif ($name eq "Year") {
                                     	$content .= "<li>" . $name . ": " .$value->literal_value ."</li>";
                                     } elsif ($name eq "Semester") {
                                     	$content .= "<li>" . $name . ": " .$value->literal_value ."</li>";
                                     } elsif ($name eq "Begin") {
                                     	$content .= "<li>" . $name . ": " .$value->literal_value ."</li>";
                                     } elsif ($name eq "End") {
                                     	$content .= "<li>" . $name . ": " .$value->literal_value ."</li>";
                                   	 } elsif ($name eq "Lecturer") {
                                     	$content .= "<li>" . $name . ": " .$value->literal_value ."</li>";
                                   	 }
                                   }
                                   $content .= "</ul>";
                                   $results->next_result;
                                 }
       
       					$content .= "</body>
       					</html>";
                      $header = HTTP::Headers->new(
                                      Content_Type => 'text/html; version=3.2',
                                      Content_Base => 'http://www.perl.org/');
                     my $res = HTTP::Response->new( HTTP_OK, "Itsy bitsy", $header, $webheader . $content );
                     $c->send_response($res);
                     $content = ""; ### clear content for new requests....
                                 } else {
									$c->send_error(404);  
									$content = "";                               	
                                 }
                 	}else {
                 		$c->send_error(404);
                 		$content = "";
                 	}
                 } else {
                     $c->send_error(404);
                     $content = "";
                 }
         }
     }
     $c->close;
     undef($c);
 }

## UNDEFINE the model and the db for clean and in older versions of perl
$model = undef;
$storage = undef;